//
//  RecommondViewController.m
//  网易公开课项目
//
//  Created by 林 艺 on 13-11-10.
//  Copyright (c) 2013年 Marklin. All rights reserved.
//
//  推荐视图

#import "RecommondViewController.h"
#import "RecommondView.h"
#import "LoadDataViewController.h"
#import "CourseModel.h"
#import "UIImageView+WebCache.h"
#import "DetailViewController.h"
#import "HistoryViewController.h"
#import "ASIHTTPRequest.h"
#import "LoadCourseDataManager.h"

@interface RecommondViewController ()

@end

@implementation RecommondViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"今日推荐";
    }
    return self;
}



- (void)viewDidLoad
{
    [super viewDidLoad];
    [self _initRecommondData];
    [self _initBarButtonItem];
    [self _initScrollView];
    [self _initPageControl];
    [self _initBlackAlertView];
}

- (void)_initRecommondData
{
    LoadCourseDataManager *dataManager = [LoadCourseDataManager shareInstance];
    if (_recommondCourses != nil)
    {
        [_recommondCourses removeAllObjects];
        _recommondCourses = nil;
    }
    _recommondCourses =[NSMutableArray arrayWithArray:[dataManager loadRecommondData]];
}

- (void)_initBlackAlertView
{
    _blackAlertView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 160, 140)];
    _blackAlertView.backgroundColor = [UIColor blackColor];
    _blackAlertView.layer.cornerRadius = 10;
    _blackAlertView.center = CGPointMake(160, 160);
    _blackAlertView.alpha = 0;
    _blackAlertView.hidden = YES;
    
    _checkMark = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 37, 37)];
    _checkMark.backgroundColor = [UIColor clearColor];
    _checkMark.image = [UIImage imageNamed:@"37x-Checkmark.png"];
    _checkMark.center = CGPointMake(160/2, 140/2);
    _checkMark.hidden = YES;
    [_blackAlertView addSubview:_checkMark];
    
    _myAIV = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    _myAIV.frame = CGRectMake(0, 0, 50, 50);
    _myAIV.center = CGPointMake(160/2, 60);
    _myAIV.hidesWhenStopped = YES;
    [_blackAlertView addSubview:_myAIV];
    
    _recommondLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 120, 30)];
    _recommondLabel.center = CGPointMake(160/2, 140*3/4);
    _recommondLabel.backgroundColor = [UIColor clearColor];
    _recommondLabel.textColor = [UIColor whiteColor];
    _recommondLabel.font = [UIFont systemFontOfSize:15];
    _recommondLabel.textAlignment = NSTextAlignmentCenter;
    [_blackAlertView addSubview:_recommondLabel];
    [self.view addSubview:_blackAlertView];
}

- (void)_initPageControl
{
    _pageControl = [[SMPageControl alloc] initWithFrame:CGRectMake(110, 320, 100, 40)];
    _pageControl.numberOfPages = 6;
    _pageControl.currentPage = 0;
    _pageControl.defersCurrentPageDisplay = YES;
    _pageControl.indicatorDiameter = 13.0f;
    _pageControl.indicatorMargin = 1.0f;
    _pageControl.currentPageIndicatorImage = [UIImage imageNamed:@"tabholder_active_ipad.png"];
    _pageControl.pageIndicatorImage = [UIImage imageNamed:@"tabholder_ipad.png"];
    [self.view addSubview:_pageControl];
}

- (void)_initScrollView;
{
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 380)];
    _scrollView.backgroundColor = [UIColor clearColor];
    _scrollView.contentSize = CGSizeMake(320*_recommondCourses.count, 380);
    _scrollView.delegate = self;
    _scrollView.pagingEnabled = YES;
    [self.view addSubview:_scrollView];
    
    for (int i = 0; i < _recommondCourses.count; i ++)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"RecommondView" owner:nil options:nil];
        RecommondView *view = nib[0];
        view.frame = CGRectMake(320*i, 0, 320, 380);
       
        //添加数据模型中的数据
        CourseModel *model = [_recommondCourses objectAtIndex:i];
        view.titleLabel.text = model.title;
        view.classLabel.text = model.tags;
        view.schoolLabel.text = model.school;
        view.playCountLabel.text = [NSString stringWithFormat:@"%@", model.playcount];
        view.updatePlayCountLabel.text = [NSString stringWithFormat:@"%@", model.updatedPlaycount];
        [view.courseImageView setImageWithURL:[NSURL URLWithString:model.imagePath]];
        view.courseImageView.tag = RecommondViewImageViewTag+i;
        view.courseImageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(courseImageViewTap:)];
        [view.courseImageView addGestureRecognizer:tap];
       
        [_scrollView addSubview:view];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = RecommondViewButtonTag+i;
        button.frame = CGRectMake(100+320*i, 279, 120, 44);
        [button setBackgroundImage:[UIImage imageNamed:@"course_btn.png"] forState:UIControlStateNormal];
        [button setTitle:@"查看详情" forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:16];
        [button addTarget:self action:@selector(courseClicked:) forControlEvents:UIControlEventTouchUpInside];
        
        [_scrollView addSubview:button];
    }
}

- (void)courseImageViewTap:(UITapGestureRecognizer *)tap
{
    DetailViewController *detail = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
    CourseModel *model = [_recommondCourses objectAtIndex:tap.view.tag-RecommondViewImageViewTag];
    detail.videoCode = model.plid;
    
    //隐藏tabbarView;
    UIView * view =[self.tabBarController valueForKey:@"tabbarView"];
    view.frame = CGRectMake(-320, view.frame.origin.y, view.frame.size.width, view.frame.size.height);
    
    [self.navigationController pushViewController:detail animated:YES];

}


- (void)_initBarButtonItem
{
    //刷新按钮
    UIButton *refresh = [UIButton buttonWithType:UIButtonTypeCustom];
    [refresh setImage:[UIImage imageNamed:@"refresh_ico.png"] forState:UIControlStateNormal];
    [refresh setImage:[UIImage imageNamed:@"refresh_ico_active_iphone.png"] forState:UIControlStateHighlighted];
    [refresh addTarget:self action:@selector(refreshClicked) forControlEvents:UIControlEventTouchUpInside];
    refresh.frame = CGRectMake(0, 0, 50, 34);
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithCustomView:refresh];
    self.navigationItem.leftBarButtonItem = leftButton;
    
    //历史记录按钮
    UIButton *history = [UIButton buttonWithType:UIButtonTypeCustom];
    [history setImage:[UIImage imageNamed:@"history_btn.png"] forState:UIControlStateNormal];
    [history setImage:[UIImage imageNamed:@"history_btn_active.png"] forState:UIControlStateHighlighted];
    [history addTarget:self action:@selector(historyClicked) forControlEvents:UIControlEventTouchUpInside];
    history.frame = CGRectMake(0, 0, 50, 34);
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithCustomView:history];
    self.navigationItem.rightBarButtonItem = rightButton;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark --
#pragma mark 自定义按键
- (void)historyClicked
{
    HistoryViewController *history = [[HistoryViewController alloc] init];
    
    //隐藏tabbarView;
    UIView * view =[self.tabBarController valueForKey:@"tabbarView"];
    view.frame = CGRectMake(-320, view.frame.origin.y, view.frame.size.width, view.frame.size.height);
    
    [self.navigationController pushViewController:history animated:YES];
}

- (void)refreshClicked
{
    LoadCourseDataManager *dataManger = [LoadCourseDataManager shareInstance];
    [dataManger.courseData removeAllObjects];
    _recommondLabel.text = @"正在刷新";
    [UIView animateWithDuration:0.3 animations:^{
        _blackAlertView.hidden = NO;
        _blackAlertView.alpha = 0.8;
        [_myAIV startAnimating];
    }];

    [dataManger loadDataFromInternet];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadDataFinished:) name:kTurnToMainViewNotification object:nil];
}

- (void)loadDataFinished:(NSNotification *)note
{
    [self _initRecommondData];
    [_scrollView removeFromSuperview];
    [_pageControl removeFromSuperview];
    [self _initScrollView];
    [self _initPageControl];
    [self.view bringSubviewToFront:_blackAlertView];
    [UIView animateWithDuration:0.3 animations:^{
        _blackAlertView.hidden = NO;
        _blackAlertView.alpha = 0.8;
        [_myAIV stopAnimating];
        _checkMark.hidden = NO;
        _recommondLabel.text = @"刷新成功";
    }];
    [[NSNotificationCenter defaultCenter] postNotificationName:KRefreshNotification object:nil];
    [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(blackAlertViewDismiss) userInfo:nil repeats:NO];
}

- (void)blackAlertViewDismiss
{
    [UIView animateWithDuration:1.5 animations:^{
        _blackAlertView.alpha = 0;
        _checkMark.hidden = YES;
        _blackAlertView.hidden = YES;
    }];
}

- (void)courseClicked:(UIButton *)button
{
    DetailViewController *detail = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
    CourseModel *model = [_recommondCourses objectAtIndex:button.tag-RecommondViewButtonTag];
    detail.videoCode = model.plid;
    
    //隐藏tabbarView;
    UIView * view =[self.tabBarController valueForKey:@"tabbarView"];
    view.frame = CGRectMake(-320, view.frame.origin.y, view.frame.size.width, view.frame.size.height);
    
    [self.navigationController pushViewController:detail animated:YES];
}

#pragma mark --
#pragma mark UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger index = scrollView.contentOffset.x/ScreenWidth;
    _pageControl.currentPage = index;
}

#pragma mark --
#pragma mark viewWillAppear
-(void)viewWillAppear:(BOOL)animated
{
    UIView * view =[self.tabBarController valueForKey:@"tabbarView"];
    [UIView animateWithDuration:0.35 animations:^{
        view.frame = CGRectMake(0, view.frame.origin.y, view.frame.size.width, view.frame.size.height);
    }];
}

@end
